import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;
import 'package:www.znpigai.teacher/home_page/subject_tab_component/item/state.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/nav.dart';
import 'package:www.znpigai.teacher/utils/progress_dialog.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';

Effect<SubjectState> buildEffect() {
  return combineEffects(<Object, Effect<SubjectState>>{
    Lifecycle.initState: _onInit,
    SubjectAction.onSave: _onSave,
    SubjectAction.onEdit: _onEdit,
    SubjectAction.onPost: _onPost,
  });
}

void _onInit(Action action, Context<SubjectState> ctx) async {
  Future.delayed(Duration.zero, () async {
    var pr = new ProgressDialog(ctx.context)..setMessage('请等待...');
    pr.show();

    HttpResult result = await Http.get(
        '/correct/teacher/api/homework/entrepot/detail.mvc',
        query: {'id': ctx.state.id});
    pr.hide();

    if (result.success) {
      ctx.dispatch(SubjectActionCreator.result(result.data));
    } else {
      Util.alertFail(result, ctx.context);
    }
  });
}

void _onSave(Action action, Context<SubjectState> ctx) async {
  var pr = new ProgressDialog(ctx.context)..setMessage('请等待...');
  pr.show();

  HttpResult result = await Http.post(
      '/correct/teacher/api/homework/entrepot/save.mvc',
      isJson: true,
      data: {
        'gradeList': ctx.state.gradeList,
        'themeList': ctx.state.themeList,
        'typeList': ctx.state.typeList,
        'articleTypeList': ctx.state.articleTypeList,
        'tagList': ctx.state.tagList,
        'keywordList': ctx.state.keywordList,
        'title': ctx.state.title,
        'demand': ctx.state.demand,
        'ideation': ctx.state.ideation,
      });
  pr.hide();

  if (result.success) {
    Util.alert('保存成功', ctx.context);
    Navigator.of(ctx.context).pop();
  } else {
    Util.alertFail(result, ctx.context);
  }
}

void _onEdit(Action action, Context<SubjectState> ctx) {
  Navigator.of(ctx.context)
      .pushNamed(Nav.SUBJECT_EDIT, arguments: ctx.state)
      .then((ok) {
    if (ok == true) {
      _onInit(action, ctx);
    }
  });
}

void _onPost(Action action, Context<SubjectState> ctx) async {
  Navigator.of(ctx.context).pushNamed(Nav.HOMEWORK_POST, arguments: ctx.state);
}
